package com.lcredu.lcrliving.commodity.service.impl;

import com.lcredu.common.util.PageUtils;
import com.lcredu.common.util.Query;
import com.lcredu.lcrliving.commodity.entity.*;
import com.lcredu.lcrliving.commodity.service.*;
import com.lcredu.lcrliving.commodity.vo.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.lcredu.lcrliving.commodity.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    //装配
    @Resource
    private SpuInfoDescService spuInfoDescService;

    @Resource
    private SpuImagesService spuImagesService;

    @Resource
    private AttrService attrService;

    @Resource
    private ProductAttrValueService productAttrValueService;

    @Resource
    private SkuInfoService skuInfoService;

    @Resource
    private SkuImagesService skuImagesService;

    @Resource
    private SkuSaleAttrValueService skuSaleAttrValueService;

    /**
     * 保存saveSpuInfo对象/数据到表[会根据业务,分别保存到对应表]
     *
     * @param spuSaveVO
     * @Transactional 涉及多表事务管理
     */
    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVO spuSaveVO) {
        //1.保存到spu基本信息到commodity_spu_info,拆
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();//表中字段需要对应才能拷贝
        //2.将SpuSaveVO属性拷贝spuInfoEntity
        BeanUtils.copyProperties(spuSaveVO, spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());

        //3.将spuInfoEntity保存到commodity_spu_info(扩展,可读)
        this.saveBaseSpuInfo(spuInfoEntity);

        //保存spu的介绍图片的信息到commodity_spu_info_desc
        List<String> decript = spuSaveVO.getDecript();
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        //这里的spuInfoDescEntity里面的id是从spuInfoEntity读取出来的
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());

        //判断decript中有几个图片路径-元素
        if (decript.size() == 0) {//如果没有设置默认图片
            spuInfoDescEntity.setDecript("default.jpg");
        } else {//如果有的话就进行一个遍历,使用逗号间隔,join:遍历-拼接
            spuInfoDescEntity.setDecript(String.join(",", decript));
        }

        //保存spuInfoDescEntity
        spuInfoDescService.saveSpuInfoDesc(spuInfoDescEntity);

        //保存spu图片集
        //1.先得到images
        List<String> images = spuSaveVO.getImages();
        System.out.println("id为===》" + spuInfoEntity.getId());
        spuImagesService.saveImages(spuInfoEntity.getId(), images);

        //保存spu基本属性(多个)到commodity_product_attr_value

        //1.从spuSaveVo对象取出前端通过json基本属性
        List<BaseAttrs> baseAttrs = spuSaveVO.getBaseAttrs();

        //2.遍历baseAttrs将数据封装到ProductAttrValueEntity[?]将其收集成集合
        //业务需求，遍历，流式计算
        List<ProductAttrValueEntity> productAttrValueEntities = baseAttrs.stream().map(attr -> {
            //创建ProductAttrValueEntity
            ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
            productAttrValueEntity.setSpuId(spuInfoEntity.getId());
            productAttrValueEntity.setQuickShow(attr.getShowDesc());
            productAttrValueEntity.setAttrValue(attr.getAttrValues());
            productAttrValueEntity.setAttrSort(0);
            //前端并未携带基本属性名到vo对象,需要我们进行二次处理
            //通过attrId获取到属性信息
            AttrEntity attrEntity = attrService.getById(attr.getAttrId());
            productAttrValueEntity.setAttrName(attrEntity.getAttrName());
            productAttrValueEntity.setAttrId(attr.getAttrId());
            return productAttrValueEntity;
        }).collect(Collectors.toList());

        //3.将收集到的productAttrValueEntities批量保存
        productAttrValueService.saveProductAttr(productAttrValueEntities);

        //-保存SKU基本信息

        //1.从spuSaveVo对象取出前端通过json发送的sku基本属性
        //前端发送的sku是多个
        List<Skus> skus = spuSaveVO.getSkus();

        //2.遍历skus将sku的基本信息封装到SkuInfoEntity入库->commodity_sku_info
        if (skus != null && skus.size() > 0) {
            skus.forEach(item -> {
                //1.先创建SkuInfoEntity
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                skuInfoEntity.setSpuId(spuInfoEntity.getId());

                //处理默认图片
                String defaultImg = "https://lcrliving-10000.oss-cn-guangzhou.aliyuncs.com/%E9%BB%98%E8%AE%A4%E5%9B%BE%E7%89%87.jpg";

                for (Images image : item.getImages()) {
                    if (image.getDefaultImg() == 1) {//判断是否传入默认图片,如果有则以传入图片为默认图片
                        defaultImg = image.getImgUrl();
                    }
                }
                skuInfoEntity.setSaleCount(0l);//销量默认为0
                skuInfoEntity.setSkuDefaultImg(defaultImg);
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setPrice(item.getPrice());
                skuInfoEntity.setSkuName(item.getSkuName());
                skuInfoEntity.setSkuSubtitle(item.getSkuSubtitle());
                skuInfoEntity.setSkuTitle(item.getSkuTitle());

                //保存sku基本信息到表
                skuInfoService.saveSkuInfo(skuInfoEntity);

                //-保存sku的图片集信息(一个sku可以对应多个图片)

                //1.从sku取出图片集集合->遍历->SkuImagesEntity
                //2.收集集合中过滤掉imgurl为空的情况
                List<SkuImagesEntity> SkuImagesEntities = item.getImages().stream().map(img -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setImgSort(0);
                    skuImagesEntity.setDefaultImg(img.getDefaultImg());
                    skuImagesEntity.setImgUrl(img.getImgUrl());
                    skuImagesEntity.setSkuId(skuInfoEntity.getSkuId());
                    return skuImagesEntity;
                }).filter(img -> {
                    return StringUtils.isNotBlank(img.getImgUrl());
                }).collect(Collectors.toList());


                //2.批量添加
                skuImagesService.saveBatch(SkuImagesEntities);

                //-保存sku销售属性到SkuSaleAttrValueEntity->commodity_sku_sale_attr_value
                //-一个sku具有多个销售属性

                //1.得到销售属性
                List<Attr> attrs = item.getAttr();
                //2.遍历attrs将数据封装到SkuSaleAttrValueEntity
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = attrs.stream().map(attr -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    skuSaleAttrValueEntity.setSkuId(skuInfoEntity.getSkuId());
                    skuSaleAttrValueEntity.setAttrId(attr.getAttrId());
                    skuSaleAttrValueEntity.setAttrName(attr.getAttrName());
                    skuSaleAttrValueEntity.setAttrValue(attr.getAttrValue());
                    skuSaleAttrValueEntity.setAttrSort(0);
                    return skuSaleAttrValueEntity;
                }).collect(Collectors.toList());

                //3.批量保存
                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);
            });
        }

    }

    /**
     * 保存spu的基本信息
     *
     * @param spuInfoEntity
     */
    @Override
    public void saveBaseSpuInfo(SpuInfoEntity spuInfoEntity) {
        this.baseMapper.insert(spuInfoEntity);
    }


    //    通过携带的检索条件进行分页检索
    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {

        QueryWrapper<SpuInfoEntity> queryWrapper = new QueryWrapper<>();

        //处理检索条件-key
        String key = (String) params.get("key");
        if (StringUtils.isNotBlank(key)) {
            System.out.println("enter");
            //id等于,名称-模糊
            queryWrapper.and(w -> {
                w.eq("id", key).or().like("spu_name", key);
            });
        }
            //检索条件-状态
            String status = (String) params.get("status");
            if (StringUtils.isNotBlank(status)) {
                queryWrapper.eq("publish_status", status);
            }

            //检索条件-品牌id
            String brandId = (String) params.get("brandId");
            if (StringUtils.isNotBlank(brandId) && !"0".equalsIgnoreCase(brandId)) {
                queryWrapper.eq("brand_id", brandId);
            }

            //检索条件分类id
            String catalogId = (String) params.get("catalogId");
            if (StringUtils.isNotBlank(catalogId) && !"0".equalsIgnoreCase(catalogId)) {
                queryWrapper.eq("catalog_id", catalogId);
            }

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void up(Long spuId) {
        this.baseMapper.updateSpuStatus(spuId, 1);
    }

    @Override
    public void down(Long spuId) {
        this.baseMapper.updateSpuStatus(spuId, 2);
    }

}
